package semSimilarity.word;

import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import semSimilarity.test.Pair;
import sparql.SparqlWNTest;


public class SimilarityCacheSimulator implements WordSimilarity {
	
	private Map<Pair<String>, Double> map;
	
	public SimilarityCacheSimulator(){
		try {
	
		
			this.map= new HashMap<Pair<String>, Double>();

			Scanner fileIn = new Scanner(new File(new URI("".getClass().getResource("/cacheInit.txt").toString())));
			
			while (fileIn.hasNext()) {
				Scanner line = new Scanner(fileIn.nextLine());
				
				String s1="", s2="";
				Double sim;
				s1= line.next();
				s2=line.next();
				sim= Double.parseDouble(line.next());
				this.map.put(new Pair<String>(s1, s2), sim);
			}

		
		}
		catch (Exception e) {
		e.printStackTrace();
	}	}

	@Override
	public double generateWordSimilarity(String s1, String s2) {
		
		double similarity=0 ;
		if (s1==null || s2==null)
			return similarity;
		if (s1.equalsIgnoreCase(s2)) {
			similarity=1;
			//String strings = s1+" "+s2+" ";
			//System.out.println(strings+" "+similarity+" (equality)");
			
		}
		else similarity = similarityMapping(s1,s2);
		return similarity;
	}

	private double similarityMapping(String s1, String s2) {
		Double similarity = 0.0;
		similarity = this.map.get(new Pair<String>(s1, s2));
		if (similarity!=null) {
			//String strings = s1+" "+s2+" ";
			//System.out.println(strings+" "+similarity+" (cache)");
			return similarity;
		}
		
		else {
			similarity = SparqlWNTest.getInstance().generateWordSimilarity(s1, s2);
			this.map.put(new Pair<String>(s1, s2), similarity);
		}
			return similarity;
	}

}
